package com.uduemc.biso.node.web.service.byfeign.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.dto.FeignPageUtil;
import com.uduemc.biso.node.core.common.entities.SitePage;
import com.uduemc.biso.node.core.common.feign.CSiteFeign;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.feign.SPageFeign;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.service.byfeign.PageService;

import cn.hutool.core.collection.CollUtil;

@Service
public class PageServiceImpl implements PageService {

	@Autowired
	private CSiteFeign cSiteFeign;

	@Autowired
	private SPageFeign sPageFeign;

	// 默认对page 的排序
	public static String DEFAULT_ORDER_BY_CLAUSE = "`parent_id` ASC, `order_num` ASC, `id` ASC";

	@Override
	public SitePage getSitePageByFeignPageUtil(FeignPageUtil feignPageUtil) throws IOException {
		RestResult restResult = cSiteFeign.getSitePageByFeignPageUtil(feignPageUtil);
		return RestResultUtil.data(restResult, SitePage.class);
	}

	@Override
	public SitePage getSitePageByHostPageId(long hostId, long pageId) throws IOException {
		RestResult restResult = cSiteFeign.getSitePageByHostPageId(hostId, pageId);
		SitePage sitePage = RestResultUtil.data(restResult, SitePage.class);
		return sitePage;
	}

	@Override
	public SPage getPageByHostPageId(long hostId, long pageId) throws IOException {
		RestResult restResult = sPageFeign.findByIdHostId(pageId, hostId);
		return RestResultUtil.data(restResult, SPage.class);
	}

	@Override
	public SPage getPageByHostSitePageId(long hostId, long siteId, long pageId) throws IOException {
		RestResult restResult = sPageFeign.findByIdHostSiteId(pageId, hostId, siteId);
		return RestResultUtil.data(restResult, SPage.class);
	}

	@Override
	public SPage getPageByHostSiteSystemId(long hostId, long siteId, long systemId) throws IOException {
		RestResult restResult = sPageFeign.findByHostSiteSystemIdOrderBy(hostId, siteId, systemId, DEFAULT_ORDER_BY_CLAUSE);
		@SuppressWarnings("unchecked")
		List<SPage> listSPage = (ArrayList<SPage>) RestResultUtil.data(restResult, new TypeReference<ArrayList<SPage>>() {
		});
		if (CollUtil.isEmpty(listSPage)) {
			return null;
		}
		return listSPage.get(0);
	}

	@Override
	public List<SPage> getPages(long hostId, long siteId) throws IOException {
		RestResult restResult = sPageFeign.findShowByHostSiteIdAndOrderBy(hostId, siteId, DEFAULT_ORDER_BY_CLAUSE);
		@SuppressWarnings("unchecked")
		List<SPage> pageData = (List<SPage>) RestResultUtil.data(restResult, new TypeReference<List<SPage>>() {
		});
		return pageData;
	}

}
